<?php
/*
 * @Author: 杨红兵 
 * @Date: 2022-08-08 11:41:32 
 * @Last Modified by: 杨红兵
 * @Last Modified time: 2022-08-08 11:44:22
 */

namespace app\libraries\utils\queue\job;

use app\libraries\utils\Trace;
use think\facade\Queue;

abstract class AsyncJob extends SyncJob
{
    /**
     * 队列名称
     *
     * @var string
     * @Author YangHB
     * @DateTime 2022-08-08 13:42:40
     *
     */
    protected string $queue = 'default';

    /**
     * 设置队列名称
     *
     * @Author YangHB
     * @DateTime 2022-08-08 13:42:47
     *
     * @param string $tmpQueue
     * @return AsyncJob
     */
    public function setQueue(string $tmpQueue): AsyncJob
    {
        $this->queue = $tmpQueue;
        return $this;
    }

    /**
     * 是否是异步队列
     * @return bool
     */
    public function isAsyncQueue(): bool
    {
        return !empty($this->queue);
    }

    /**
     * 异步抛出任务
     *
     * @Author YangHB
     * @DateTime 2022-08-08 12:38:31
     *
     * @param array $data
     * @param integer $delay
     * @return mixed
     */
    public function dispatch(array $data, int $delay = 0)
    {
        //异步任务最快5秒后执行
        $delay = $delay < 1 ? 1 : $delay;
        //异步任务，最大延时30天
        $delay = $delay > 86400 * 30 ? 86400 * 30 + rand(0, 3600) : $delay;

        /**
         * @var \think\Request
         */
        $request = app('request');
        $data = array_merge([
            'app_type' => $request->param('app_type', ''),
            'app_guid' => $request->param('app_guid', ''),
        ], $data, [
            'headers' => [
                'Call_From' => 'queue_client',
                'X_REQUEST_TRACE_ID' => Trace::getInstance()->getTraceId(),
                'X_REQUEST_PRE_ID' => Trace::getInstance()->getNowTraceId(),
            ],
        ]);

        if ($this->queue === 'default') {
            $this->queue = 'default_' . config('app.env');
        }
        $res = Queue::later($delay, static::class, $data, $this->queue);
         if ($res) {
            return true;
        }

        LogError(
            __CLASS__ . '-' . __FUNCTION__,
            '异步任务',
            '投递失败',
            compact('data', 'delay', 'res')
        );
        return false;
    }
}
